<?php
/**
 * Created by PhpStorm.
 * User: childeYin<尹少爷>
 * Date: 18/07/2018
 * Time: 8:32 AM
 */
// use Zaly\Proto\Site\ApiSiteGroupRequest;

class Api_Site_GroupController extends \BaseController
{
    private $classNameForRequest = '\Zaly\Proto\Site\ApiSiteLoginRequest';
    // private $classNameForRequest = '';
    // private $classNameForRequest = '\Zaly\Proto\Site\ApiSiteGroupRequest';
    private $classNameForResponse = '\Zaly\Proto\Site\ApiSiteLoginResponse';
    private $sessionVerifyAction = "api.session.verify";
    private $permissionJoin = \Zaly\Proto\Core\GroupJoinPermissionType::GroupJoinPermissionMember;
    private $canGuestReadMsg = false;
    private $pinyin;
    // public $siteCookieName = "zaly_site_user";
    private $maxMembers = -1;
    private $groupNameLength = 20;
    private $startGroupCreateTime;
    private $createGroupTimeOut = 60; //1分钟超时
    private $groupIdLength = 10;

    public function rpcRequestClassName()
    {
        return $this->classNameForRequest;
    }
      /**
     * @param \Zaly\Proto\Site\ApiSiteGroupRequest $request
     * 
     */
    public function rpc(\Google\Protobuf\Internal\Message $request, \Google\Protobuf\Internal\Message $transportData){
        header('Access-Control-Allow-Origin: *');
        header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
        header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
 
        //写的请求不行 加不进去
        $json_data = file_get_contents('php://input');
        // 解析 JSON 数据
        $data = json_decode($json_data, true);
        $this->pinyin = new \Overtrue\Pinyin\Pinyin();
        $this->startGroupCreateTime = time();
       

        //查询一下是否有用户
      
      
      


        // $data['buyer_id']='061cc204946cae41c136f6c80de39ec6efb2dd21';
        if($data['buyer_id']&&$data['seller_id']&&$data['order_id']){

             //  先查询用户id

             //这段逻辑都搬了 搬到nlgoin里去了
            //是否注册过---
            // $res=$this->ctx->PassportPasswordTable->getUserByUserId($data['buyer_id']);  //买家
            // $res1=$this->ctx->PassportPasswordTable->getUserByUserId($data['seller_id']); //卖家
            //     if(empty($res)){
            //         $loginName=$data['buyer_id'];
            //         $email=$data['buyer_id'];
            //         $password='123456';
            //         $nickname=$data['buyer_id'];
            //         $invitationCode='';
            //         $sitePubkPem='';
            //         $avatar='';
            //         //没有注册 注册一下
            //         $preSessionId=$this->registerUserForPassport($data['buyer_id'],$loginName, $email, $password, $nickname, $invitationCode, $sitePubkPem, $avatar);
            //     }else{
            //         $sitePubkPem =  $this->ctx->Site_Config->getConfigValue(SiteConfig::SITE_ID_PUBK_PEM);
            //         // $user = $this->verifyUserInfo($data['buyer_id'], 123456);
            //         $preSessionId = $this->generatePreSessionId($res, $sitePubkPem);
            //     }
            //     if(empty($res1)){
            //         //没有注册 注册一下
            //         $preSessionId2=$this->registerUserForPassport($data['seller_id'],$data['seller_id'], '', 123456, $data['seller_id'], '', '', '');
            //     }
            //     //买家登录
            //         $resdata=[
            //                 'preSessionId'=>$preSessionId
            //         ];
            //     echo json_encode($resdata);
            //   die;


                // $userIds=$data['buyer_id'].','.$data['seller_id'];

                //由于site和passw里的userid不一致 所以先用登录名字查询user_id

                $user = $this->ctx->SiteUserTable->getUserByLoginName($data['buyer_id']);
                $user2 = $this->ctx->SiteUserTable->getUserByLoginName($data['seller_id']);
              
                $existsUser= $this->ctx->SiteGroupUserTable->getUserIDExist([$user['userId'],$user2['userId']]);
                // var_dump(empty($existsUser));
                // die;
                $groupId='';
                if(!empty($existsUser)){
                        //不存在 并且返回的是groupid数组
                    $groupId=$existsUser['0'];
                    echo json_encode(['groupId'=>$groupId]);
                    // var_dump('群id'.$groupId);
                    die;
                }else{
                  
                    $groupProfile=$this->insertGroup($data['order_id'],'');
                    if (!$groupProfile) {
                     throw new Exception("create group failed");
                   }
                   
                     $groupId = $groupProfile['groupId'];
                     //邀请成员
                          /// 公开的直接进入
                    $userList = [
                        '0'=>$user['userId'],
                        '1'=>$user2['userId'],
                    ];
                    $this->addMemberToGroup($userList, $groupId);
                                    // 创建成功了之后，代发消息，

                $noticeText = ZalyText::$keyGroupCreate;

                $this->ctx->Message_Client->proxyGroupNoticeMessage($userId='c7c78834183243d1a48e0cd08ae829794d30385d', $groupId, $noticeText);
                echo json_encode(['groupId'=>$groupId]);
                // var_dump('不存在');
                die;
                }
              


                
                
                 var_dump('存在');
                die;
      
        }
        var_dump($data);
        echo '1111';
        die;
        $tag = __CLASS__ . '-' . __FUNCTION__;
        try {
            // $getBuyerId = $request->getBuyerId();
            // var_dump($getBuyerId);
            die;
                    //先直接查询传递进来的有没有群聊 没有就创建群聊
                    $userIds='';
                    
        } catch (Exception $ex) {
            $errorCode = $this->zalyError->errorSiteLogin;
            $errorInfo = $this->zalyError->getErrorInfo($errorCode);
            $this->setRpcError($errorCode, $errorInfo);
            $this->ctx->Wpf_Logger->error($tag, "error_msg=" . $ex->getMessage());
            throw new Exception("response is fail");
        }
    }

    private function generatePreSessionId($user, $sitePubkPem)
    {
        $preSessionId = ZalyHelper::generateStrId();

        try {
            $preSessionInfo = [
                "userId" => $user['userId'],
                "preSessionId" => $preSessionId,
                "sitePubkPem" => base64_encode($sitePubkPem)
            ];

            $this->ctx->PassportPasswordPreSessionTable->insertPreSessionData($preSessionInfo);
        } catch (Exception $ex) {
            $preSessionInfo = [
                "preSessionId" => $preSessionId,
                "sitePubkPem" => base64_encode($sitePubkPem)
            ];
            $where = [
                "userId" => $user['userId']
            ];
            $this->ctx->PassportPasswordPreSessionTable->updatePreSessionData($where, $preSessionInfo);
        }
        return $preSessionId;
    }

    // private function verifyUserInfo($loginName, $password)
    // {
    //     $tag = __CLASS__ . '->' . __FUNCTION__;
    //     $user = $this->ctx->PassportPasswordTable->getUserByLoginName($loginName);

    //     if (!$user) {
    //         $errorCode = $this->zalyError->errorExistUser;
    //         $errorInfo = $this->zalyError->getErrorInfo($errorCode);
    //         $this->setRpcError($errorCode, $errorInfo);
    //         throw new Exception("loginName is not exist");
    //     }

    //     $this->checkPasswordErrorNum($user['userId']);

    //     if (!password_verify($password, $user['password'])) {
    //         $this->insertPassportPasswordLog($user, 1);
    //         $errorCode = $this->zalyError->errorMatchLogin;
    //         $errorInfo = $this->zalyError->getErrorInfo($errorCode);
    //         $this->setRpcError($errorCode, $errorInfo);
    //         throw new Exception("loginName password is not match");
    //     }
    //     $operateDate = date("Y-m-d", time());
    //     $this->ctx->PassportPasswordCountLogTable->deleteCountLogDataByUserId($user['userId'], $operateDate);
    //     return $user;
    // }
    //创建群聊
    private function insertGroup($groupName, $groupAvatar,$userId='c7c78834183243d1a48e0cd08ae829794d30385d')
    {
        $tag = __CLASS__ . '-' . __FUNCTION__;
        try {

            if (time() - $this->startGroupCreateTime > $this->createGroupTimeOut) {
                $this->ctx->BaseTable->db->rollBack();
                $errorCode = $this->zalyError->errorGroupCreate;
                $errorInfo = $this->zalyError->getErrorInfo($errorCode);
                $this->setRpcError($errorCode, $errorInfo);
                return false;
            }
            $groupId = $this->ctx->ZalyHelper->generateStrKey($this->groupIdLength);
            $groupId = strtolower($groupId);
            $nameInLatin = $this->pinyin->permalink($groupName, "");
            $groupProfile = [
                "groupId" => $groupId,
                "name" => $groupName,
                "nameInLatin" => $nameInLatin,
                "avatar" => $groupAvatar,
                "owner" => $userId,
                "description" => "",
                "speakers" => "",
                "maxMembers" => $this->maxMembers,
                "permissionJoin" => $this->permissionJoin,
                "canGuestReadMessage" => $this->canGuestReadMsg ? 1 : 0,
                "status" => 1,
                "timeCreate" => $this->ctx->ZalyHelper->getMsectime()
            ];
            $groupOwnerInfo = [
                'groupId' => $groupId,
                'userId' => $userId,
                'memberType' => \Zaly\Proto\Core\GroupMemberType::GroupMemberOwner,
                'timeJoin' => $this->ctx->ZalyHelper->getMsectime()
            ];
            $this->ctx->BaseTable->db->beginTransaction();
            $this->ctx->BaseTable->insertData($this->ctx->SiteGroupTable->table, $groupProfile, $this->ctx->SiteGroupTable->columns);
            $this->ctx->BaseTable->insertData($this->ctx->SiteGroupUserTable->table, $groupOwnerInfo, $this->ctx->SiteGroupUserTable->columns);
            $this->ctx->BaseTable->db->commit();
            return $groupProfile;
        } catch (Exception $ex) {
            $this->ctx->Wpf_Logger->error($tag, "error_msg=" . $ex->getMessage());
            $this->ctx->BaseTable->db->rollBack();
//            $this->insertGroup($groupName, $this->groupIdLength++);
        }
    }
    //邀请加入群聊
    private function addMemberToGroup($userIds, $groupId)
    {
        $tag = __CLASS__ . "_" . __FUNCTION__;
        try {
            if (!$userIds) {
                $errorCode = $this->zalyError->errorUserIdExists;
                $errorInfo = $this->zalyError->getErrorInfo($errorCode);
                $this->setRpcError($errorCode, $errorInfo);
                throw new Exception($errorInfo);
            }
            $existsUserId = $this->ctx->SiteGroupUserTable->getUserIdExistInGroup($userIds, $groupId);
            $notExistsUserId = $userIds;
            if ($existsUserId) {
                $notExistsUserId = array_diff($userIds, $existsUserId);
            }
            if (!count($notExistsUserId)) {
                return true;
            }

            //$groupPointer
            $groupPointer = $this->ctx->SiteGroupMessageTable->queryMaxIdByGroup($groupId);

            $this->ctx->BaseTable->db->beginTransaction();
            foreach ($notExistsUserId as $userId) {

                //insert group Message pointer
//            $groupMessagePointerInfo = [];
                $this->ctx->SiteGroupMessageTable->updatePointer($groupId, $userId, "", $groupPointer);

                //insert into siteGroupUser
                $groupUserInfo = [
                    'groupId' => $groupId,
                    'userId' => $userId,
                    'memberType' => \Zaly\Proto\Core\GroupMemberType::GroupMemberNormal,
                    'timeJoin' => $this->ctx->ZalyHelper->getMsectime()
                ];
                $this->ctx->BaseTable->insertData($this->ctx->SiteGroupUserTable->table, $groupUserInfo, $this->ctx->SiteGroupUserTable->columns);
            }
            $this->ctx->BaseTable->db->commit();
        } catch (Exception $ex) {
            $this->ctx->BaseTable->db->rollback();
            $this->ctx->Wpf_Logger->error($tag, $ex->getMessage());
            $errorCode = $this->zalyError->errorGroupInvite;
            $errorInfo = $this->zalyError->getErrorInfo($errorCode);
            $this->setRpcError($errorCode, $errorInfo);
            throw new Exception("invite failed");
        }
    }
    //注册
    private function registerUserForPassport($userId,$loginName, $email, $password='123456', $nickname, $invitationCode, $sitePubkPem, $avatar = null)
    {
        try {
            $tag = __CLASS__ . '-' . __FUNCTION__;

            $this->ctx->BaseTable->db->beginTransaction();
            // $userId = ZalyHelper::generateStrId();
            $userInfo = [
                "userId" => $userId,
                "loginName" => $loginName,
                "email" => $email,
                "password" => password_hash($password, PASSWORD_BCRYPT),
                "nickname" => $nickname,
                "invitationCode" => $invitationCode,
                "timeReg" => ZalyHelper::getMsectime(),
                "avatar" => $avatar
            ];
            $this->ctx->PassportPasswordTable->insertUserInfo($userInfo);
            $preSessionId = ZalyHelper::generateStrId();

            $preSessionInfo = [
                "userId" => $userId,
                "preSessionId" => $preSessionId,
                "sitePubkPem" => base64_encode($sitePubkPem)
            ];
            $this->ctx->PassportPasswordPreSessionTable->insertPreSessionData($preSessionInfo);

            $this->ctx->BaseTable->db->commit();
            return $preSessionId;
        } catch (Exception $ex) {
            $this->ctx->Wpf_Logger->error($tag, "error_msg=" . $ex);
            $this->ctx->BaseTable->db->rollback();
            throw new Exception($ex);
        }
    }
    //站点注册
    private function registerSite($userId,$loginName,$nickname,$nameInLatin){
        $userProfile = [
            "userId" => $userId,
            "loginName" => $loginName,
            "loginNameLowercase" => strtolower($loginName),
            "nickname" => $nickname,
            "nicknameInLatin" => $nameInLatin,
            "countryCode" => 86,
            "phoneId" => '',
            "timeReg" => $this->ctx->ZalyHelper->getMsectime(),
        ];
    }
}